using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using System.Security;

namespace PoshXmpp
{
    [Cmdlet(VerbsCommon.New, "Client", SupportsShouldProcess = false, DefaultParameterSetName = "SecureLogin")]
    public class NewClientCommand : PSCmdlet
    {

        #region Parameters

        [Parameter(Position = 0, ParameterSetName = "CredentialLogin",
            Mandatory = true,
            ValueFromPipeline = true,
            HelpMessage = "A PSCredential consisting of your JabberId and Password")]
        public PSCredential Credential { get; set; }


        [Parameter(Position = 0, ParameterSetName = "InsecureLogin",
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Jabber Id for Login")]
        [Parameter(Position = 0, ParameterSetName = "SecureLogin",
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Jabber Id for Login")]
        [Alias("UserName")]
        [ValidateNotNullOrEmpty]
        public string JabberId { get; set; }

        [Parameter(Position = 1,ParameterSetName="InsecureLogin",
            Mandatory = true,
            HelpMessage = "Jabber Login Password")]
        [ValidateNotNullOrEmpty]
        public string Password { get; set; }

        [Parameter(Position = 1,ParameterSetName="SecureLogin",
            Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Jabber Login Password")]
        //[Alias("Password")]
        [ValidateNotNullOrEmpty]
        public SecureString SecurePassword { get; set; }


        [Parameter(Position = 2,
            Mandatory = false,
            HelpMessage = "Help Text")]
        public string HttpServer { get; set; }
        #endregion

        protected override void ProcessRecord()
        {
            XmppClient client = null;
            switch (ParameterSetName)
            {
                case "CredentialLogin":

                    client = XmppClientFactory.CreateXmppClient(Credential.UserName, Credential.Password, HttpServer);
                    break;
                case "SecureLogin":
                    client = XmppClientFactory.CreateXmppClient(JabberId, SecurePassword, HttpServer);
                    break;
                case "InsecureLogin":
                    SecureString pw = new SecureString();
                    foreach (char c in Password)
                    {
                        pw.AppendChar(c);
                    }
                    client = XmppClientFactory.CreateXmppClient(JabberId, pw, HttpServer);
                    break;
            }
            this.SessionState.PSVariable.Set("PoshXmppClient", client);
            WriteObject(client);
        }
    }
}
